<!-- 访问路径  -->
<template>
  <ContentWrap :show-border="false">
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px search-form"
      label-width="68px"
      label-position="left"
    >
      <el-form-item label="IP" prop="ip">
        <el-input
          v-model="queryParams.ip"
          class="!w-240px"
          clearable
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属地" prop="placeOrigin">
        <el-input
          v-model="queryParams.placeOrigin"
          class="!w-240px"
          clearable
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="ISP" prop="isp">
        <el-input
          v-model="queryParams.isp"
          class="!w-240px"
          clearable
          placeholder="请输入"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item class="p-0 m-0" style="border: none !important">
        <el-button @click="handleQuery" type="primary" color="#3721FF"> 搜索 </el-button>
        <el-button class="border-none" @click="resetQuery">
          <Icon class="mr-5px" icon="ant-design:clear-outlined" />
          清除条件
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap :show-border="false">
    <el-table
      v-loading="loading"
      :data="list"
      :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
      class="mt-4 mb-4 rounded-lg"
    >
      <el-table-column label="访问页面类型" min-width="90" prop="pageType" />
      <el-table-column label="访问地址" min-width="90" prop="accessAddress">
        <template #default="{ row }">
          <a :href="row.accessAddress" target="_blank">{{ row.accessAddress }}</a>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" min-width="90" prop="productName" />
      <el-table-column label="a/b商品" prop="productType" width="180" />
      <el-table-column label="动作" prop="action" width="180" />
      <el-table-column :formatter="dateFormatter" label="访问时间" prop="accessTime" width="180" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 正常删除弹窗 -->
  <ComfirmPops
    ref="deletePopsRef"
    :show-icon="false"
    width="500px"
    :show-dot="true"
    type="idTips"
    title="删除"
    :id="delSelected"
    @confirm="getDeletePops"
  >
    <template #content>
      <p class="text-center">确定删除吗？</p>
    </template>
  </ComfirmPops>
  <!-- IP拉黑弹窗 -->
  <ComfirmPops
    ref="ipPopsRef"
    :show-icon="false"
    width="700px"
    :show-dot="true"
    type="radio"
    title="新增"
    @confirm="getIpPops"
  >
    <template #content>
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        label-position="left"
        class="w-[100%] pl-10px pr-20px"
      >
        <el-row>
          <el-col :span="15">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择">
                <el-option label="IP" value="ip" />
                <el-option label="域名" value="domain" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="ip">
          <el-input v-model="formData.reason" type="textarea" :rows="7" placeholder="请输入..." />
        </el-form-item>
        <el-form-item label="备注" prop="reason">
          <el-input v-model="formData.reason" type="textarea" :rows="7" placeholder="请输入..." />
        </el-form-item>
      </el-form>
    </template>
  </ComfirmPops>
  <BatchImport
    ref="batchImportRef"
    :show-dot="true"
    width="40%"
    title="导入模板"
    @close="isBatchImport = false"
  />
</template>
<script lang="ts" setup>
import { TabsPaneContext } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import { dateFormatter } from '@/utils/formatTime'
import ComfirmPops from '@/components/ComfirmPops/index.vue'
import BatchImport from '@/components/BatchImport/index.vue'
import { defaultProps, handleTree, treeToString } from '@/utils/tree'
import { fenToYuan } from '@/utils'
import download from '@/utils/download'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { WebAccessRecordApi } from '@/api/website/record'
defineOptions({ name: 'AccessPath' })
const formDataRef = ref() // 表单的Ref
const deletePopsRef = ref() // 删除弹窗的Ref
const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
// const { push } = useRouter() // 路由跳转
const ipPopsRef = ref() // IP拉黑弹窗的Ref
const loading = ref(false) // 列表的加载中
const exportLoading = ref(false) // 导出的加载中
const total = ref(0) // 列表的总页数
// const isAddCopy = ref(false) // 是否复制
// const copyId = ref(0) // 复制的ID
const list = ref<ProductSpuApi.Spu[]>([]) // 列表的数据
const delSelected = ref(0) // 删除的ID
const isBatchImport = ref(false) // 是否显示批量导入
const batchImportRef = ref() // 批量导入的Ref
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  recordId: route.query.id as string,
  ip: '',
  placeOrigin: '',
  isp: ''
  // tabType: 0,
  // name: '',
  // categoryId: undefined,
  // createTime: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref
const formData = ref({
  type: 'ip', // 类型
  ip: '',
  reason: ''
}) // IP拉黑表单数据
const rules = ref({
  ip: [{ required: true, message: '请输入拉黑IP', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入拉黑原因', trigger: 'blur' }]
}) // IP拉黑表单验证规则
// 搜索关键词
const searchText = ref('')
// 已选中的地区
const selectedRegions = ref([])
const router = useRouter() // 路由

// const goSetNavigation = () => {
//   router.push({ name: 'SetNavigation' })
// }
const getIpPops = () => {
  //   if (formData.value.ip == '') {
  //     message.error('请输入拉黑IP')
  //     return
  //   }
  //   if (formData.value.reason == '') {
  //     message.error('请输入拉黑原因')
  //     return
  //   }
  formDataRef.value.validate(async (valid) => {
    if (valid) {
      submitForm()
      ipPopsRef.value.hide()
    } else {
      message.error('请填写完整信息')
    }
  })
}
const handleBatchImport = () => {
  batchImportRef.value.show()
}
const submitForm = () => {
  loading.value = true
  try {
    // await ProductSpuApi.addIp(formData.value)
    message.success('IP拉黑成功')
    getList() // 刷新列表
    loading.value = false
    formData.value.ip = ''
    formData.value.reason = ''
  } catch (error) {
    message.error('IP拉黑失败')
    loading.value = false
  }
}
// 根据搜索词过滤选项
const filteredOptions = (filters) => {
  return filters.filter((item) => item.text.includes(searchText.value))
}
const handleAddIp = () => {
  ipPopsRef.value.show()
}
// 筛选逻辑
const filterHandler = (value, row) => {
  return selectedRegions.value.includes(row.region)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WebAccessRecordApi.getWebAccessPathPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 切换 Tab */
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.value.tabType = tab.paneName as number
  getList()
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  delSelected.value = id
  deletePopsRef.value.show()
}
const getDeletePops = async (res: boolean, id: number) => {
  console.log('isConfirm', res, id)

  if (res) {
    // await ProductSpuApi.deleteSpu(id)
    message.success('删除成功')
    // deletePopsRef.value.hide()
  } else {
    // deletePopsRef.value.hide()
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 新增或修改 */
// const openForm = (id?: number) => {
//   // 修改
//   if (typeof id === 'number') {
//     push({ name: 'ProductSpuEdit', params: { id } })
//     return
//   }
//   // 新增
//   push({ name: 'ProductSpuAdd' })
// }

// /** 查看商品详情 */
// const openDetail = (id: number) => {
//   push({ name: 'ProductSpuDetail', params: { id } })
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductSpuApi.exportSpu(queryParams.value)
    download.excel(data, '商品列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分类的节点的完整结构 */
const categoryList = ref() // 分类树
const formatCategoryName = (categoryId: number) => {
  return treeToString(categoryList.value, categoryId)
}

/** 激活时 */
onActivated(() => {
  getList()
})

/** 初始化 **/
onMounted(async () => {
  // 解析路由的 categoryId
  if (route.query.categoryId) {
    queryParams.value.categoryId = route.query.categoryId
  }
  // 获得商品信息
  //   await getTabsCount()
  await getList()
  // 获得分类树
  const data = await ProductCategoryApi.getCategoryList({})
  categoryList.value = handleTree(data, 'id', 'parentId')
})
</script>
<style scoped>
@import '@/styles/website.scss';
</style>
